package myexchange

import myexchange.PlayerActionType;

class TurnController {
	
	def scaffold = Turn
	
	CardService cardService
	ExchangeService exchangeService
	GameService gameService
	TurnService turnService
	
	
    def startTurn = {
		Player player = Player.get(session.user.id)
		turnService.enqueAction(player, null, null, PlayerActionType.START)
    	render(template:"startTurn")
    }
	
    def trade ={
		Player player = Player.get(session.user.id)
		def exchangeList = Exchange.findAllByPlayer(player)
		Map shareCount = [:]
		for (Exchange exchange : exchangeList){
			shareCount << [(exchange.share.id):exchange.quantity]
		}
		def shareList =  Share.list()
		turnService.enqueAction(player, null, null, PlayerActionType.TRADE)
    	render(template:"trade", model: [shareList:shareList, shareCount:shareCount, player:player])
    }
    
    def tradeShare = {
		Map shareIds = params.shareId
		Map quantities = params.quantity
		
		Player player = session.user
		int quantity
		Share share
		shareIds.each{
			share = Share.read(it.value)
			quantity = "".equals(quantities[it.key])?0:Integer.parseInt(quantities[it.key])
			if(quantity != 0){
				Trade trade = new Trade([
						player:player,
						quantity:quantity,
						share:share
					]).save()
				turnService.enqueAction(player, null, trade, PlayerActionType.TRADE)
			}
		}
		
		forward(action:"endTurn")
    			
    }
    
    def selectCard = {
		Player player = Player.get(session.user.id) 
		if (player.cards.size() < 6){
			Card card = cardService.getNextCard()
			player.cards.add(card)
			player.save(failOnError: true)
		}
		
		turnService.enqueAction(player, null, null, PlayerActionType.CARD)

    	render(template:"selectCard", model: [player:player])
    }
	
	def playCard = {
		def cardId =params.cardId
		render(template:"playCard", model: [card:Card.get(cardId), shareList:Share.list()])
	}
	
	def executeCard = {
		Player player = Player.get(session.user.id) 
		(0..1).each{i->
			def mod = params.modification["${i}"]
			String mId = mod.id
			Share share = Share.findByName(mod.share)
			if ((mId != null)&&(share != null)){
				Modification m = Modification.get(mId)
				m.share = share
				m.save(failOnError: true);
			}
		}
		Card card = Card.read(params.card.id)
		turnService.enqueAction(player, card, null, PlayerActionType.CARD)
		redirect (action: "endTurn")
	}
	
	def endTurn = {
		Player player = session.user
		turnService.enqueAction(player, null, null, PlayerActionType.END)
		redirect(controller:"game",action:"loadActionPanel")
	}
	
	def endTurnAll = {
		turnService.endTurn()
	}
	
	
}
